//
//  KMSegmentedHeaderView.m
//  CNstorm
//
//  Created by 陈家将 on 16/11/16.
//  Copyright © 2016年 chenjiajiang. All rights reserved.
//

#import "KMSegmentedHeaderView.h"

@interface KMSegmentedHeaderView ()

@property (strong, nonatomic) UISegmentedControl *segmentedCtr;
@property (copy, nonatomic) SelectedItemBlock callBack;

@end


@implementation KMSegmentedHeaderView

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        UISegmentedControl *segmentedCtr= [[UISegmentedControl alloc]initWithFrame:CGRectZero];
        //            segmentedControl.frame = CGRectMake(10.0f, 10.0f, MainScreenWidth-20.0f, 30.0f);
        segmentedCtr.tintColor = COLOR_RED;
        [segmentedCtr setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:COLOR_RED,NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
        [segmentedCtr setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil] forState:UIControlStateSelected];
        [segmentedCtr addTarget:self action:@selector(selectedSegmentAction:)forControlEvents:UIControlEventValueChanged];  //添加委托方法
        segmentedCtr.layer.cornerRadius = 6.0f;
        segmentedCtr.layer.borderWidth = 0.5f;
        segmentedCtr.layer.borderColor = COLOR_TEXT_HIGHT.CGColor;
        [self addSubview:segmentedCtr];
        self.segmentedCtr = segmentedCtr;
        
        [segmentedCtr mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.mas_top).offset(SPACE);
            make.left.mas_equalTo(self.mas_left).offset(SPACE);
            make.right.mas_equalTo(self.mas_right).offset(-SPACE);
            make.height.mas_equalTo(30.0);
        }];
    }
    
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    if (self.segmentedCtr.numberOfSegments != self.titles.count) {
        [self.segmentedCtr removeAllSegments];// 先清空先前的所有
        
        for (NSInteger index = 0; index < self.titles.count; index++) {
            [self.segmentedCtr insertSegmentWithTitle:self.titles[index] atIndex:index animated:NO];
        }
        
        self.segmentedCtr.selectedSegmentIndex = self.selectedIndex;//设置默认选择项索引
    }
}



- (void)selectedItemCompletion:(SelectedItemBlock)completion {
    _callBack = completion;
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    self.segmentedCtr.selectedSegmentIndex = selectedIndex;
    [super setSelectedIndex:selectedIndex];
}

- (void)selectedSegmentAction:(UISegmentedControl *)segmentedControl {
    NSInteger index = segmentedControl.selectedSegmentIndex;
    if (_callBack) {
        _callBack(index);
    }
}

@end
